package com.hefan.common.ons.listener;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.TopicRegistryDev;
import com.hefan.common.ons.TopicRegistryTest;
import com.hefan.common.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author: ninglijun
 * @date: 15/5/22
 * @time: 下午2:39
 * @description:
 */
@Component
public class LocalTestListener implements GLLMessageListener, ApplicationContextAware {

    private ApplicationContext applicationContext;

    Logger logger = LoggerFactory.getLogger(LocalTestListener.class);

    @Override
    public TopicRegistry getTopicRegistry() {
        return TopicRegistry.HEFANTV_TEST2;
    }
    @Override
    public TopicRegistryDev getTopicRegistryDev() {
        return null;
    }

    @Override
    public TopicRegistryTest getTopicRegistryTest() {
        return null;
    }

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        String realTopic = message.getTag();
//        logger.info("consume message , topic: {}, realTopic : {}, msg_body: {}", message.getTopic(), realTopic, new String(message.getBody()));
        GLLMessageListener realListener = getRealListenerByTopic(realTopic);
        if (realListener == null) {
            return Action.ReconsumeLater;
        }
        return realListener.consume(message, consumeContext);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    private GLLMessageListener getRealListenerByTopic(String topic) {
        Map<String, GLLMessageListener> beanMap = applicationContext.getBeansOfType(GLLMessageListener.class);
        for (Map.Entry<String, GLLMessageListener> entry : beanMap.entrySet()) {
            GLLMessageListener listener = entry.getValue();
            if (StringUtils.equals(listener.getTopicRegistry().getTopic(),topic)) {
                return listener;
            }
        }
        return null;
    }

}
